<?php
namespace Weixin\Controller;
use Think\Controller;
class PayController extends Controller {

    public function index(){
		die;
		header("Content-type: text/html; charset=utf-8");
		$tid = I('tid','1',intval);
		if(empty($tid))$this->error('非法交易');
		$viptype = viptype($tid);
		
		import('Class/weixin/lib/WxPay_Config',APP_PATH,'.php');
		import('Class/weixin/example/WxPay_JsApiPay',APP_PATH,'.php');
		import('Class/weixin/example/log',APP_PATH,'.php');
		import('Class/weixin/lib/WxPay_Api',APP_PATH,'.php');
		import('Class/weixin/lib/WxPay_Data',APP_PATH,'.php');

		//初始化日志
		$logHandler= new \CLogFileHandler("../logs/".date('Y-m-d').'.log');
		$log = \Log::Init($logHandler, 15);


		//①、获取用户openid
		$tools = new \JsApiPay();
		//$openId = $tools->GetOpenid();
		$openId = 'oJ5Bnv8k8IAVUQGneoy5_bPffg3Q';

		//②、统一下单
		$input = new \WxPayUnifiedOrder();
		$input->SetBody($viptype['name']);
		$input->SetAttach($viptype['name']);
		//$input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));
		$input->SetOut_trade_no('JD010'.date("ymdHis").getStr(1,5));
		//$input->SetTotal_fee($viptype['money']*100);//支付费用
		$input->SetTotal_fee('1');//支付费用
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag($viptype['describe']);
		$input->SetNotify_url("http://wx.bjkunya.com".U('pay_notify'));
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($openId);
		$WxPayApi = new \WxPayApi();
		$order = $WxPayApi->unifiedOrder($input);//统一下单

		p($input);
		p($order);

		$jsApiParameters = $tools->GetJsApiParameters($order);//JSAPI支付信息
		//p(json_decode($jsApiParameters,true));

		//获取共享收货地址js函数参数
		//$editAddress = $tools->GetEditAddressParameters();

		//p($editAddress);

		//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
		/**
		 * 注意：
		 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
		 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
		 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
		 */
			
		 $this->data  = $input;
		 $this->type  = $viptype;
		 $this->jsApi = $jsApiParameters;
		 $this->title = '我要充值';
		 $this->display('pay');
    }
 

	//微信支付回调地址
	public function pay_notify(){
		//$data = $GLOBALS["HTTP_RAW_POST_DATA"];
		$data = file_get_contents("php://input");

		if($data){
			logw($data,'/weixin/notify');
		}

		/*$xml ="<xml><appid><![CDATA[wxe535d0d4d274e775]]></appid>
				<attach><![CDATA[高级会员]]></attach>
				<bank_type><![CDATA[CFT]]></bank_type>
				<cash_fee><![CDATA[1]]></cash_fee>
				<fee_type><![CDATA[CNY]]></fee_type>
				<is_subscribe><![CDATA[Y]]></is_subscribe>
				<mch_id><![CDATA[1297226401]]></mch_id>
				<nonce_str><![CDATA[len6qaans6fpy345rzgtsekpvki0vhjr]]></nonce_str>
				<openid><![CDATA[o7wgCwUkAQ35SqOFjqIPPIy7W_ZU]]></openid>
				<out_trade_no><![CDATA[JD0102017051813275850558]]></out_trade_no>
				<result_code><![CDATA[SUCCESS]]></result_code>
				<return_code><![CDATA[SUCCESS]]></return_code>
				<sign><![CDATA[4CDAE96C93B13E6855CC3DC0FBF9C884]]></sign>
				<time_end><![CDATA[20170518132805]]></time_end>
				<total_fee>1</total_fee>
				<trade_type><![CDATA[JSAPI]]></trade_type>
				<transaction_id><![CDATA[4008732001201705181352111667]]></transaction_id>
				</xml>";
		[appid] => wxe535d0d4d274e775
		[attach] => 楂樼骇浼氬憳
		[bank_type] => CFT
		[cash_fee] => 1
		[fee_type] => CNY
		[is_subscribe] => Y
		[mch_id] => 1297226401
		[nonce_str] => len6qaans6fpy345rzgtsekpvki0vhjr
		[openid] => o7wgCwUkAQ35SqOFjqIPPIy7W_ZU
		[out_trade_no] => JD0102017051813275850558 //商户订单号
		[result_code] => SUCCESS   //业务结果
		[return_code] => SUCCESS
		[sign] => 4CDAE96C93B13E6855CC3DC0FBF9C884
		[time_end] => 20170518132805 //支付完成时间
		[total_fee] => 1
		[trade_type] => JSAPI
		[transaction_id] => 4008732001201705181352111667 //微信支付订单号
		*/
		$data = xmlarray($data);
		if(!$data){
			die;
		}
		logw($data,'/weixin/pay');
		$return ="<xml>
			  <return_code><![CDATA[SUCCESS]]></return_code>
			  <return_msg><![CDATA[OK]]></return_msg>
			</xml>";
		
		$result_code = $data['result_code']; //业务结果
		$total_fee   = $data['total_fee'];
		$order_sn    = $data['out_trade_no'];
		$openid      = $data['openid'];
		$paytime     = $data['time_end'];
		
		//支付成功
		if($result_code == 'SUCCESS'){
			$field    = ['id','openid','item_id','status','uid'];
			$where    = ['openid'=>$openid,'order_sn'=>$order_sn];
			$order    = M('order')->field($field)->where($where)->find();
			$user_info= M('user')->field(['is_pay','openid','nickname','vip_end_time','vip_type'])->where(['id'=>$order['uid']])->find();
			$is_pay   = $user_info['is_pay'];//M('user')->where(['id'=>$order['uid']])->getField('is_pay');
			if($order){
				if($order['status']){
					echo $return;
					die;
				}
				$uporder = array('id'=>$order['id'],'paytime'=>strtotime($paytime),'status' =>'1','transaction_id'=>$data['transaction_id']);
				
				//开始计时VIP服务
				$vip     = viptype($order['item_id']);
				$H       = substr($paytime,8,2);
				$I       = substr($paytime,10,2);
				$S       = substr($paytime-1,-2);

				//如果是续费  vip时间没有过期 则累加
				if($user_info['vip_type']){
					if($user_info['vip_end_time'] > time()){
						$u_ymd  = date('Ymd',$user_info['vip_end_time']);
						$uY     = substr($u_ymd,0,4);
						$um     = substr($u_ymd,4,2);
						$ud     = substr($u_ymd,-2);
						$endtime= mktime($H,$I,$S,$um+$vip['expire'],$ud,$uY);                   //结束时间
					}else{
						$endtime= mktime($H,$I,$S,date('m')+$vip['expire'],date('d'),date('Y')); //结束时间
					}
				}else{
					$endtime= mktime($H,$I,$S,date('m')+$vip['expire'],date('d'),date('Y'));//结束时间
				}

				$user    = array('vip_type'=>$order['item_id'],'vip_end_time'=>$endtime,'id'=>$order['uid']);
				if(!$is_pay){
					$user['is_pay']=1;
				}

				M()->startTrans();
				try{
					$chance = $vip['chance'];
					M('order')->save($uporder);
					
					//非礼包 更新VIP
					if($vip['type'] != '3'){
						M('user')->save($user);
					}
					
					/*赠送首次充值发布次数*/
					$is_free = C('IS_FREE');
					if($is_free && !$is_pay){
						$months  = C('FREE_MONTH');
						$detail  = ['uid'=>$order['uid'],'type'=>1,'chance'=>$months,'time'=>time()];
						M('send_detail')->add($detail);
						$chance = $chance+$months;
					}
					/*End*/

					M('user')->where(['id'=>$order['uid']])->setInc('chance',$chance);

					S('endtime_'.$order['uid'],null);//删除缓存
					S('jsApi_'.$order['item_id'],null);
					M()->commit();
					logw($user,'/weixin/vip');
					//logw($uporder,'/weixin/order');

					//微信通知
					$total_fee = $total_fee/100;
					if($vip['type'] == '3'){
						$notice_type = 1;
						$data_wx = array(
							'name'   => $vip['name'],       //商品名称
							'money'  => "￥{$total_fee}元", //支付金额
							'chance' => $vip['chance'],     //条数
						);
						$notice_type = 1;
					}else{
						$data_wx = array(
							'vip'    => $vip['name'],        //商品名称
							'money'  => "￥{$total_fee}元",  //支付金额
							'status' => '充值成功',          //状态
							'expire' => $vip['expire'].'个月,可发布'.$vip['chance'].'条',
							//'url'    => 'http://'.$_SERVER['HTTP_HOST'].'/Home/User/index.html',
						);
						$notice_type = 0;
					}
					$data_wx['url']      = 'http://'.$_SERVER['HTTP_HOST'].'/Home/User/usercode.html';
					$data_wx['nickname'] = urldecode($user_info['nickname']);
					$this->weixin_notice($openid,$data_wx,$notice_type);
					//微信通知

					echo $return;
				}catch (\Exception $e) {
					M()->rollback();
					die;
				}

			}
		}
	}


	/**
	 * 微信模版消息
	 * @openid   微信OPENDI
	 * @data     发送的数据
	 * @type     模版通知id  0会员充值通知  1订单支付成功
	 */
	public function weixin_notice($openid,$data,$type=0){
		if(!$openid){
			return false;
		}
		import('Class.Weixin',APP_PATH);//实例化微信模版
		$weixin= new \Weixin();

		$token = access_token();
		/*$data1  = array(
			'nickname'=> '说不出口', //昵称
			'vip'     => '铂金会员', //会员类型
			'money'   => '120元',   //支付金额
			'status'  => '充值成功', //状态
			'expire'  => '6个月,发布条数750条，连续发布7天，可赠送30条', //状态
		);
		$data  = array(
			'nickname'=> '说不出口', //昵称
			'name'    => '发布小礼包', //会员类型
			'money'   => '10元',   //支付金额
			'chance'  => '100条，连续发布7天，可赠送30条', //状态
			'url'     => 'http://192.168.1.171', //状态
		);*/

		$send = $weixin->send_wxmsg($openid,$data,$type,$token);

		return $send;
	}

	





/*ignore_user_abort();//关掉浏览器，PHP脚本也可以继续执行.
set_time_limit(3000);// 通过set_time_limit(0)可以让程序无限制的执行下去
$interval=5;// 每隔5s运行

//方法1--死循环
do{
echo '测试'.time().'<br/>'; 
sleep($interval);// 等待5s    
}while(true);

//方法2---sleep 定时执行
require_once './curlClass.php';//引入文件

$curl = new httpCurl();//实例化
$stime = $curl->getmicrotime();
for($i=0;$i<=10;$i++){

echo '测试'.time().'<br/>'; 
sleep($interval);// 等待5s

}
ob_flush();
flush();
$etime = $curl->getmicrotime();
echo '<hr>';
echo round(($etime-stime),4);//程序执行时间
*/




	//End
}

